SpringBoot和前端数据交互(js,jQuery,thymeleaf) | 您所在的位置:网站首页 › springboot 模板引擎 一行 › SpringBoot和前端数据交互(js,jQuery,thymeleaf) |
一、后台接收URL拼接参数 后台代码: @GetMapping("/item/{code}") //对应的链接为:/item/10001 public List getProduct(@PathVariable("code") String productCode) { //your code }二、后台接收查询参数 后台代码: @GetMapping("/detail") //对应的链接为:/detail?code=&name= public String listMaterial(@RequestParam("code") String productCode, @RequestParam("name") String productName) { //your code }前台代码: 1.通过表单提交 2.通过JavaScript使用Formdata对象提交
三、后台接收json 后台代码: @PostMapping("/add") public MaterialStandard addProduct(@RequestBody Product product ){ //your code }前台代码: 1.通过JavaScript提交 var product = new Product(); $.ajax({ url:"/add", type:"POST", data:JSON.stringify(product), contentType: "application/json;charset=UTF-8", accept : "*/*", success : function () { console.log("Successfully"); } }); //使用了jQuery,原生JavaScript同理四、接收文件 后台代码: @PostMapping("/upload") public String upload(@RequestParam("file") MultipartFile file) { //your code }前台代码: 1.通过表单提交 2.通过JavaScript使用FormData对象提交 var fileInput = $("#file"); var selectedFile = fileInput[0].files[0]; var data = new FormData(); data.append("file", selectedFile); $.ajax({ url: '/upload', type: 'POST', data: data, contentType: false, //不设置内容类型 processData: false, //不处理数据 accept : "*/*", success : function () { console.log("Successfully"); } }); 使用了jQuery,原生JavaScript同理五、关于thymeleaf模板和Ajax 前台的视图模版我使用的是thymeleaf,它是SpringBoot官方推荐的一个html5模版引擎,SpringBoot官方不推荐使用jsp,SpringBoot官网也是使用这个模版引擎做的。 通过jQuery的ajax向Controller发送请求,在js回调函数中处理返回的数据,页面我用bootstrap快速的做了一个表格,渲染列表使用了一个叫做avalonjs的迷你mvvm框架,生成虚拟dom,可以参考官网。[链接]:http://avalonjs.coding.me/)
HTML页面示例: Hello World {{@text}} id 姓名 性别 年龄 角色 {{el.id}} {{el.name}} {{el.sex}} {{el.age}} {{el.role}}js文件: var viewmodel = avalon.define({ //id必须和页面上定义的ms-controller名字相同,否则无法控制页面 $id: "viewmodel", datalist: {}, text: "请求数据", request: function () { $.ajax({ type: "post", url: "/hello/data", //向后端请求数据的url data: {}, success: function (data) { $('button').removeClass("btn-primary").addClass("btn-success").attr('disabled', true); viewmodel.datalist = data; viewmodel.text = "数据请求成功,已渲染"; } }); } });
|
今日新闻 |
推荐新闻 |
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 |